package com.nami.conver.types.util;

import com.nami.conver.types.constants.CommonConst;

public class L2ConverCacheKeyUtil {

    /**
     * 求模取余，分桶数量
     */
    public static final int HASH_THRESHOLD = 10000;
//    public static final int HASH_THRESHOLD = 1; // 测试使用
//    public static final int CONVER_INFO_BUCKET_SIZE = 1; // 测试使用
    public static final int CONVER_INFO_BUCKET_SIZE = 100000;

    public static String buildConverInfoKey(String appKey, String userId) {
        return CommonConst.CACHE_PREFIX + appKey + ":conver:info:bucket:" + infoBucket(userId);
    }

//    private String buildConverItemKey(ConverModel converDomain) {
////        String[] ids = {converItem.getUserId(), converItem.getTargetId()};
////        Arrays.sort(ids, Comparator.naturalOrder());
//        return buildConverItemKey(converDomain.getUserId(), converDomain.getTargetId());
//    }

    public static String convertBucketId(String key) {
        return calculateBucket(key, HASH_THRESHOLD);
    }

    public static String infoBucket(String key) {
        return calculateBucket(key, CONVER_INFO_BUCKET_SIZE);
    }


    public static String buildConverItemKey(String userId, String targetId) {
        return userId + "_" + targetId;
    }

    /**
     * 生成查询我所有的会话 一个排序 key
     *
     * @param appKey
     * @param userId
     * @return
     */
    public static String buildConverZAddSortKey(String appKey, String userId) {
        return CommonConst.CACHE_PREFIX + appKey + ":conver:_sort:bucket:" + convertBucketId(userId) + ":" + userId;
    }

    private static String calculateBucket(String key, int threshold) {
        int hash = key.hashCode();
        int bucket = (hash ^ (hash >>> 16)) % threshold;
        if (bucket < 0) {
            bucket += threshold;
        }
        return bucket + "";
    }


}
